package com.razorthink.shell.commands.essential;

import java.sql.SQLException;

import com.razorthink.shell.core.AbstractCommand;
import com.razorthink.shell.utils.CommandLogger;
import com.razorthink.shell.utils.DerbyDB;

public class Logout extends AbstractCommand {
	DerbyDB db;

	public Logout(String baseCommand, int params) {
		super(baseCommand, params);
	}

	@Override
	public void execute() {
		try {
			db = DerbyDB.getInstance();
		} catch (SQLException e) {
			CommandLogger.logError(e);
			return;
		}
		if (super.getCommandParser().getParamCount() > 0) {
			CommandLogger.logInfo("Logout command cannot have param");
			return;
		}
		String oldPrompt = super.getAppContext().getPrompt();
		String restorePrompt = "";
		if (oldPrompt.contains("@")) {
			restorePrompt = oldPrompt.split("@")[1];
			super.setEnvVar("loggedin", null);
			super.getAppContext().setPrompt(restorePrompt);
			CommandLogger.logInfo("'" + oldPrompt.split("@")[0]
					+ "' has logged out.");
		} else {
			super.setEnvVar("loggedin", null);
			CommandLogger.logInfo("Can't log out since no user is logged in.");
		}
	}

	@Override
	public String getDescription() {
		return "logout";
	}

	@Override
	public String getUsage() {
		return "logout";
	}

}
